const authService = require('../services/authService');
const User = require('../models/user');
const checkToken = (req, res, next) => {
//   console.log('checkToken:', req.headers);
  console.log('baseUrl:', req.baseUrl);
//   console.log('method:', req.method);
  // 登录接口不校验token
  if (req.baseUrl === '/api/login' || req.method === 'OPTIONS') {
    return next();
  }

  const token = req.headers.authorization;
  console.log('token:', token);
  if (!token) {
    return res.status(401).json({
      code: 401,
      message: '未授权',
      data: null
    });
  }

  let decodedToken;
  try {
    decodedToken = authService.decodeToken(token.split(' ')[1]);

    if (!decodedToken) {
      return res.status(401).json({
        code: 401,
        message: '无效的token',
        data: null
      });
    }
  } catch (error) {
    return res.status(401).json({
      code: 401,
      message: '无效的token',
      data: null
    });
  }

  req.user = decodedToken;
  next();
};
const requireActive = async (req, res, next) => {
  console.log('requireActive:', req.body);
  const { email } = req.body
  const user = await User.findOne({ email })
  if (!user) {
    return res.status(201).json({
      code: 201,
      message: '用户不存在'
    });
  }
  if (!user.active) {
    return res.status(201).json({
      code: 201,
      message: '用户未激活'
    });
  }
  if (!user.role) {
    return res.status(201).json({
      code: 201,
      message: '用户未分配角色'
    });

  }

  next();

}

module.exports = {
    checkToken,
    requireActive,
};


